import { useRequest } from 'vue-hooks-plus';
import { useMessage } from '@/hooks/useMessage';
import {
  UseRequestOptions,
  UseRequestPlugin,
  UseRequestService,
} from 'vue-hooks-plus/lib/useRequest/types';
export function useListPage<
  TData,
  TParams extends unknown[] = unknown[],
  PluginsOptions extends UseRequestPlugin<TData, TParams>[] = UseRequestPlugin<
    TData,
    TParams
  >[],
>(config: {
  queryApi: UseRequestService<TData, TParams>;
  deleteApi?: (...args: any) => Promise<any>;
  queryConfig?: UseRequestOptions<
    TData,
    TParams,
    PluginsOptions extends (infer P)[]
      ? P extends UseRequestPlugin<TData, TParams, infer R>
        ? R
        : never
      : never
  >;
}) {
  const message = useMessage();

  const queryParams = reactive({});
  const queryFormRef = ref(); // 搜索的表单
  const req = useRequest(
    (async (req: any) =>
      config
        .queryApi(
          // @ts-ignore
          {
            ...queryParams,
            ...req,
          } as any
        )
        .then(res => {
          return (res || []).map((item, index) => {
            return {
              ...item,
              _index: index + 1,
            };
          });
        })) as any as UseRequestService<TData, TParams>,
    config.queryConfig
  );
  const { runAsync: getList, data } = req;

  /** 搜索按钮操作 */
  const handleQuery = () => {
    // @ts-ignore
    getList();
  };

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields();
    handleQuery();
  };

  /** 删除按钮操作 */
  const handleDelete = async (...args: any) => {
    // 删除的二次确认
    await message.delConfirm();
    if (config.deleteApi) {
      // 发起删除
      await config.deleteApi(...args);
      message.success('删除成功');
      // 刷新列表
      // @ts-ignore
      await getList();
    }
  };
  return {
    queryFormRef,
    handleQuery,
    handleDelete,
    resetQuery,
    ...req,
    queryParams,
    list: req.data,
  };
}
